package cn.wonderland.community.controller;

import cn.wonderland.community.service.IUnitService;
import cn.wonderland.community.domain.Unit;
import cn.wonderland.community.query.UnitQuery;
import cn.wonderland.basic.util.AjaxResult;
import cn.wonderland.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/unit")
public class UnitController {
    @Autowired
    public IUnitService unitService;


    /**
     * 保存和修改公用的
     *
     * @param unit 传递的实体
     * @return AjaxResult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Unit unit) {

        if (unit.getId() != null) {
            unitService.update(unit);
        } else {
            unit.setCreateTime(new Date());
            unitService.add(unit);
        }

        return AjaxResult.me().success();
    }

    /**
     * 删除对象信息
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            unitService.delete(id);
            return AjaxResult.me().success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().fail();
        }
    }

    //获取用户
    @GetMapping("/{id}")
    public Unit get(@PathVariable("id") Long id) {
        return unitService.findById(id);
    }


    /**
     * 查看所有的员工信息
     *
     * @return
     */
    @GetMapping()
    public List<Unit> list() {

        return unitService.findAll();
    }


    /**
     * 分页查询数据
     *
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping("/list")
    public PageList<Unit> json(@RequestBody UnitQuery query) {
        return unitService.queryByPage(query);
    }

    /**
     * 根据楼栋id查询单元
     * @return PageList 分页对象
     */
    @PostMapping("/findUnitByBuildingId/{id}")
    public List<Unit> findUnitByBuildingId(@PathVariable("id") Long id) {
        return unitService.findUnitByBuildingId(id);
    }
}
